package com.qiku.utils;

import com.qiku.entity.Article;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class BeanCopyUtils {

    public BeanCopyUtils() {
    }

    public static <V> V copyBean(Object source , Class<V> clazz){
        //通过反射创建对象
        V result = null;
        try {
            result = clazz.newInstance();
            //属性拷贝
            BeanUtils.copyProperties(source,result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回结果
        return result;
    }

    public static <T,V> List<V> copyBeanList(List<T> list, Class<V> clazz){
        //stream流的方法
//        return list.stream().map(new Function<T, V>() {
//           @Override
//           public V apply(T obj) {
//               return (V) copyBean(obj, clazz);
//           }
//       }).collect(Collectors.toList());

        List<V> beanList = new ArrayList<>();
        for (T t : list) {
            beanList.add((V)copyBean(t,clazz));
        }
        return beanList;
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        List<Article> list = new ArrayList<>();
        Article article = new Article();
        for (int i = 1; i <= 5; i++) {
            article.setId(1L + 1);
            article.setTitle("小说"+ i);
            list.add(article);
        }
        List<Article> articleList = copyBeanList(list, Article.class);
        System.out.println(articleList);
    }


}
